package com.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.domain.ChatMessage;
import com.example.service.ChatMessageService;
import com.example.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: 不是菜鸡爱编程
 * @Date: 2024/01/29/19:37
 * @Description:
 */
@RestController
@RequestMapping("/message")
public class ChatMessageController {
    @Autowired
    private ChatMessageService chatMessageService;

    /**
     * 获取与好友的历史信息
     *
     * @param userId   用户id
     * @param friendId 朋友id
     * @return {@link R}
     */
    @GetMapping("/{userId}/{friendId}")
    public R getMessagesWithFriend(@PathVariable Integer userId,@PathVariable Integer friendId){
        // 查询与好友的聊天记录
        List<ChatMessage> list = chatMessageService.list(new LambdaQueryWrapper<ChatMessage>()
                .eq(ChatMessage::getFromUser, userId).eq(ChatMessage::getToUser, friendId)
                .or()
                .eq(ChatMessage::getFromUser, friendId).eq(ChatMessage::getToUser, userId));
        // 按照时间顺序排序
        List<ChatMessage> sortedMessages = list.stream().filter(message->message.getCreateTime()!=null).sorted(Comparator.comparing(ChatMessage::getCreateTime)).collect(Collectors.toList());
        return R.ok().setData(sortedMessages);
    }
}
